from PositionalList import *


class CharacterEditor(PositionalList):
    """文本编辑器，使用位置列表ADT"""

    def __init__(self):
        super().__init__()
        self.cursor = None

    def __len__(self):
        return self.size

    def left(self):
        """将光标向左移动一位"""
        if self.before(self.cursor) is not None:
            self.cursor = self.before(self.cursor)

    def right(self):
        """将光标向右移动一位"""
        if self.after(self.cursor) is not None:
            self.cursor = self.after(self.cursor)

    def insert(self, string):
        """在光标后面插入一个字符"""
        for char in string:
            if type(char) is str and len(char) == 1:
                if not self.is_empty():
                    self.cursor = self.add_after(self.cursor, char)
                else:
                    self.cursor = self.add_first(char)

    def delete(self):
        """删除光标后面的字符"""
        if not self.is_empty():
            while self.after(self.cursor) is not None:
                super().delete(self.after(self.cursor))
            if self.before(self.cursor) is not None:
                self.left()
                super().delete(self.after(self.cursor))
            else:
                super().delete(self.cursor)

    def __str__(self):
        characters = ''
        cursor_p = 0
        current = self.first()
        for i in range(self.size):
            if current == self.cursor:
                cursor_p = i
            if current is not None:
                characters += current.element()
                current = self.after(current)
        msg = characters + '\n' + ' ' * cursor_p + '↑'
        return msg


if __name__ == '__main__':
    ce = CharacterEditor()
    ce.insert('test')
    print(ce)


    def start():
        while True:
            show()
            raw_in = input()
            ce.insert(raw_in)


    def show():
        print(ce)


    start()
